from rest_framework.views import APIView
from rest_framework.viewsets import ModelViewSet
from rest_framework.response import Response
from rest_framework.authentication import BasicAuthentication
from .sers import *
from mutils import SMSCode
import mutils


class CodeAPIView(APIView):
    def post(self,request):
        ser=CodeSer(data=request.data)
        ser.is_valid(raise_exception=True)
        phone=ser.validated_data.get('phone')

        sms=SMSCode()
        code=sms.random_code()

        Code.objects.create(code=code,phone=phone)

        return Response({'验证码': code})

class UserViewSet(ModelViewSet):
    queryset = User.objects.all()
    serializer_class = UserSer

class TokenAPIView(APIView):
    authentication_classes = [BasicAuthentication]
    def post(self,request):
        key=str(datetime.datetime.now())
        key=mutils.md5(key)

        Token.objects.update_or_create(user=request.user,defaults={'key':key})

        return Response({'token':key})
